import React, { memo, useRef, useEffect } from "react";

import { PhoneLoginWrapper } from './style.js'

import { validateMobile } from './rules'
import { getVerifyCode, VerifyCode, LoginIn } from "@/services/login"
import { Button, Form, Input, message } from 'antd';

export default memo(function PhoneLogin() {
  const FormRef = useRef()
  const onFinish = (values) => {
  };
  const onFinishFailed = (errorInfo) => {
  };
  const hanldeGetVerifyCode = () => {
    let phone = FormRef.current.getFieldValue('telephoneNum');
    if (phone) {
      validateMobile("", phone).then(_ => {
        getVerifyCode(phone)
      })
    }
  }
  const handleLogin = () => {
    let phone = FormRef.current.getFieldValue('telephoneNum');
    let verify = FormRef.current.getFieldValue('validateNum');
    const params = {
      phone,
      captcha: verify
    }
    if (phone) {
      validateMobile("", phone).then(_ => {
        VerifyCode(phone, verify).then(res => {
          LoginIn(params)
        }).catch(err => {
        })
      })
    }
  }
  return (
    <PhoneLoginWrapper>
      <Form
        ref={FormRef}
        name="basic"
        onFinish={onFinish}
        onFinishFailed={onFinishFailed}
        autoComplete="off"
      >
        <Form.Item
          label="手机号"
          name="telephoneNum"
          rules={[
            {
              required: true,
              message: '请输入手机号',
            },
            {
              validator: validateMobile
            }
          ]}
        >
          <Input />
        </Form.Item>

        <Form.Item
          label="验证码"
          name="validateNum"
        >
          <Input />
        </Form.Item>
        <Form.Item
          wrapperCol={{
            offset: 8,
            span: 16,
          }}
        >
          <Button type="primary" htmlType="submit" onClick={_ => hanldeGetVerifyCode()}>
            获取验证码
          </Button>
          <Button type="primary" htmlType="submit" onClick={_ => handleLogin()}>
            登录
          </Button>
        </Form.Item>
      </Form>
    </PhoneLoginWrapper>

  );
})